import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileClient {
    private static String FILE_PATH = "./file_to_send.txt";
    private static String FILE_NAME = "file_to_send.txt";

    public static void main(String[] args) {
        if (args.length > 0) {
            FILE_PATH = args[0];
            // 在这里使用filePath参数进行后续操作
            System.out.println("传递的文件路径为：" + FILE_PATH);
            File file = new File(FILE_PATH);
            FILE_NAME = file.getName();
            System.out.println("传递的文件名为：" + FILE_NAME);
        }
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldPrepender(4));
                        }
                    })
                    .option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.connect("localhost", 8888).sync();
            System.out.println("Connected to server.");

            ByteBuf messageBuffer = Unpooled.copiedBuffer(FILE_NAME, io.netty.util.CharsetUtil.UTF_8);
            future.channel().writeAndFlush(messageBuffer).sync();

            // 读取图片文件为字节数组
            byte[] imageData = Files.readAllBytes(Paths.get(FILE_PATH));

            // 发送图片字节数组
            ByteBuf buf = Unpooled.wrappedBuffer(imageData);
            future.channel().writeAndFlush(buf).sync();

            // 同步阻塞，等待与该 Channel 相关联的所有的资源（如网络连接）被正确关闭，然后才会继续执行后面的代码。
            // future.channel().closeFuture().sync();

            // 异步关闭连接
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.addListener((ChannelFutureListener) f -> {
                // 连接关闭后的处理逻辑
                System.out.println("Connection closed.");
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}